package com.chaodev.base.controller;

;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.model.*;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dto.ButtonDTO;
import com.chaodev.base.dto.MenuDTO;
import com.chaodev.base.service.IButtonService;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.service.IMenuService;
import com.chaodev.base.utils.JwtUtil;
import com.chaodev.base.utils.RequestParamerMap;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/menu")
public class MenuController {

    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;

    @Qualifier("menuServiceImpl")
    @Autowired
    private IMenuService menuService;

    @Autowired
    private IButtonService buttonService;

    @Value("${myserver.name}")
    private String myserverName;

    /**
     * @Description: 获取左侧菜单树
     * @Author: xy
     * @CreateDate: 2019/12/27 14:12
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:12
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/getUserMenu")
    @ResponseBody
    @ApiOperation(value = "获取左侧菜单树")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getMenuTitle(@RequestBody MenuQuery menu, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("P_NODE_ID", "0");
            map.put("P_ROLE_ID", userInfo.getRoleId());
            map.put("P_USER_ID", userInfo.getUserId());
            map.put("P_KEYWORD", menu.getKeyword());
            List<Map<String, Object>> list = menuService.getMenuTitle(map);
            Iterator<Map<String, Object>> it = list.iterator();
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            while (it.hasNext()) {
                Map<String, Object> resultMap1 = it.next();
                Map<String, Object> dataMap1 = new HashMap<>();
                dataMap1.put("createDate", "");
                dataMap1.put("createUser", "");
                dataMap1.put("id", resultMap1.get("NODE_ID"));
                dataMap1.put("menuCode", resultMap1.get("NODE_ID"));
                dataMap1.put("menuIcon", resultMap1.get("ICON"));
                dataMap1.put("menuName", resultMap1.get("TEXT_NAME"));
                dataMap1.put("menuType", 1);
                dataMap1.put("menuUrl", resultMap1.get("URL"));
                dataMap1.put("orgCode", "");
                dataMap1.put("parentCode", resultMap1.get("PARENT_MENU_ID"));
                dataMap1.put("remark", "");
                dataMap1.put("sort", "");
                dataMap1.put("status", resultMap1.get("STATE"));
                dataMap1.put("updateDate", "");
                dataMap1.put("updateUser", "");
                dataMap1.put("parentMenuName", resultMap1.get("PARENT_MENU_NAME"));
                resultList.add(dataMap1);
            }
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(resultList);

            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd("", "获取菜单树", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd("", "获取菜单树", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 获取菜单按钮
     * @Author: xy
     * @CreateDate: 2019/12/27 14:22
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:22
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @RequestMapping(value = "/GetMenuButton", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取菜单按钮")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getMenuButton(@RequestBody @ApiParam(value = "菜单信息") Menu menu, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("P_MENU_ID", menu.getMenuId());
            map.put("P_ROLE_ID", userInfo.getRoleId());
            List<ButtonDTO> list = menuService.getMenuButton(map);
            result.setCode(0);
            result.setData(list);

            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(menu.toString(), "获取菜单按钮", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(menu.toString(), "获取菜单按钮", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 获取菜单列表
     * @Author: xy
     * @CreateDate: 2019/12/27 14:24
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:24
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/getMenuTreeGrid")
    @ApiOperation(value = "获取菜单列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result menuQuery(@RequestBody @ApiParam(value = "分页传入参数") DataPageVO dataPage, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            //设置默认排序方式
            if (null == dataPage.getOrder() || "".equals(dataPage.getOrder())) {
                dataPage.setOrder("DESC");
            }
            Map<String, Object> map = new HashMap<>();
            map.put("P_PAGE", dataPage.getPage());
            map.put("P_PAGESIZE", dataPage.getRows());
            map.put("P_KEYWORD", dataPage.getKeyword());
            map.put("P_SORTNAME", dataPage.getSort());
            map.put("P_SORTORDER", dataPage.getOrder());
            map.put("P_USERID", userInfo.getUserId());
            map.put("U_DEPART_ID", userInfo.getDepartId());
            PageInfo<MenuDTO> menuPage = menuService.menuQuery(map);

            Map<String, Object> reMap = new HashMap<>();
            reMap.put("total", menuPage.getTotal());
            reMap.put("rows", menuPage.getList());
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(reMap);
            Result logResult = new Result();
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logResult.setServerID(result.getServerID());
            logService.logAdd(dataPage.toString(), "获取菜单列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dataPage.toString(), "获取菜单列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 获取菜单上级树
     * @Author: xy
     * @CreateDate: 2019/12/27 14:33
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:33
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @RequestMapping(value = "/getMenuOptions", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取菜单上级树")
    @SuppressWarnings("all")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getMenuParentTree(@RequestBody @ApiParam(value = "节点信息") Tree tree, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("P_NODE_ID", tree.getCurrnode());
            map.put("P_ROLE_ID", userInfo.getRoleId());
            List<Map<String, Object>> list = menuService.getMenuParentTree(map);
            Iterator<Map<String, Object>> it = list.iterator();
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            while (it.hasNext()) {
                Map<String, Object> resultMap = it.next();
                Map<String, Object> dataMap = new HashMap<>();
                if (resultMap.get("PARENT_MENU_ID").toString().equals("0")) {
                    dataMap.put("value", resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString());
                    dataMap.put("label", resultMap.get("TEXT_NAME") == null ? "" : resultMap.get("TEXT_NAME").toString());
                    String nodeid = resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString();
                    List<Map<String, Object>> listChild = new ArrayList<>();
                    if (resultMap.get("STATE").equals("closed")) {
                        listChild = GetChildMap(nodeid, list);
                    }
                    dataMap.put("children", listChild);
                    resultList.add(dataMap);
                }
            }
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(resultList);

            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(tree.toString(), "获取菜单上级树", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(tree.toString(), "获取菜单上级树", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    public List<Map<String, Object>> GetChildMap(String PID, List<Map<String, Object>> list) {
        List<Map<String, Object>> listChild = new ArrayList<>();
        for (Map<String, Object> listChildMap : list) {
            if (listChildMap.get("PARENT_MENU_ID").toString().equals(PID)) {
                Map<String, Object> dataMap1 = new HashMap<>();
                dataMap1.put("value", listChildMap.get("NODE_ID") == null ? "" : listChildMap.get("NODE_ID").toString());
                dataMap1.put("label", listChildMap.get("TEXT_NAME") == null ? "" : listChildMap.get("TEXT_NAME").toString());
                List<Map<String, Object>> listChildnew = new ArrayList<>();
                if (listChildMap.get("STATE").equals("closed")) {
                    listChildnew = GetChildMap(listChildMap.get("NODE_ID").toString(), list);
                }
                dataMap1.put("children", listChildnew);
                listChild.add(dataMap1);
            }
        }
        return listChild;
    }

    /**
     * @Description: 新增菜单
     * @Author: xy
     * @CreateDate: 2019/12/27 14:47
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:47
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @SuppressWarnings("all")
    @ApiOperation(value = "新增菜单")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result menuAdd(@RequestBody @ApiParam(value = "菜单信息") Menu menu, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        Map<String, Object> requestMap = RequestParamerMap.getParamerMap(request);
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            menu.setCreateUser(userInfo.getUserId());
            menu.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            boolean flag = menuService.menuAdd(menu);
            if (flag == true) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("提交成功");
            } else {
                result.setCode(-1);
                result.setMsg("提交失败");
            }
            logService.logAdd(menu.toString(), "新增/修改菜单", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(menu.toString(), "新增/修改菜单", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 菜单删除
     * @Author: xy
     * @CreateDate: 2019/12/27 14:51
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:51
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/delete")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "删除菜单")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    @Transactional(rollbackFor = Exception.class)
    public Result menuDelete(@RequestBody @ApiParam(value = "菜单消息") Menu menu, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            //删除菜单信息
            boolean flag = menuService.menuDelete(menu);
            //删除菜单按钮信息
            buttonService.menuBtnDel(menu.getMenuId());
            if (flag) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("删除成功");
            } else {
                result.setCode(-1);
                result.setMsg("删除失败");
            }
            logService.logAdd(menu.toString(), "删除菜单", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(menu.toString(), "删除菜单", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 获取权限菜单树
     * @Author: xy
     * @CreateDate: 2019/12/27 14:33
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:33
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @RequestMapping(value = "/getMenuZtree", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取权限菜单树")
    @SuppressWarnings("all")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public List<MenuDTO> getMenuZtree(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("P_NODE_ID", "");
        List<MenuDTO> list = menuService.getMenuZtree(map);
        Result logResult = new Result();
        logResult.setCode(0);
        logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
        logService.logAdd("", "获取权限菜单树", "SUCCESS", logResult.toString(), null, request);
        return list;
    }


    /**
     * @Description: 获取功能菜单树
     * @Author: xy
     * @CreateDate: 2019/12/27 14:33
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:33
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @RequestMapping(value = "/getMenuZtreeBtn", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取功能菜单树")
    @SuppressWarnings("all")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public List<MenuDTO> getMenuZtreeBtn(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        map.put("P_NODE_ID", "");
        List<MenuDTO> list = menuService.getMenuZtreeBtn(map);
        Result logResult = new Result();
        logResult.setCode(0);
        logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
        logService.logAdd("", "获取功能菜单树", "SUCCESS", logResult.toString(), null, request);
        return list;
    }
}
